<template>
	<view class="captcha-btn-container" @click="get_form">
		{{run_time? `${second}秒后重新获取`: '获取验证码'}}
	</view>
</template>

<script>
	export default {
		name: "CaptchaBtn",
		data() {
			return {
				run_time: false,	// 是否正在倒计时
				timer: null,
				second: 60
			};
		},
		methods: {
			get_form() {
				if (!this.run_time) {
					this.$emit('get_form', this._send_code)
				}
			},
			async _send_code(form) {
				const {
					phone
				} = await form.validateField(['phone'])

				this.run_time = true
				this.count_down()
				const {
					msg,
					code
				} = await this.$http.get_code({
					phone
				})
				uni.showToast({
					title: msg,
					icon: 'none'
				})
				this.$emit('get_code', code)
			},
			count_down() {
				this.timer = setInterval(() => {
					this.second--
					if (this.second <= 0) {
						clearInterval(this.timer)
						this.run_time = false
						this.second = 60
					}
				}, 1000)
			}
		},
		beforeDestroy() {
			// 如果有定时器，在组件销毁前要清除定时器
			clearInterval(this.timer)
		}
	}
</script>

<style lang="scss">
	.captcha-btn-container {
		color: #fff;
		background-color: $base-color;
		padding: 15rpx 20rpx;
		opacity: .8;
		margin-right: 20rpx;
		border-radius: 10rpx;
	}
</style>
